import path from "path";

/**
 * Generates a normalized absolute path from a file path and workspace root
 */
export function generateNormalizedAbsolutePath(filePath: string, workspaceRoot: string): string {
  const absolutePath = path.isAbsolute(filePath) ? filePath : path.join(workspaceRoot, filePath);
  return path.normalize(absolutePath);
}

/**
 * Generates a relative file path from an absolute path and workspace root
 */
export function generateRelativeFilePath(absolutePath: string, workspaceRoot: string): string {
  const normalizedAbsolutePath = path.normalize(absolutePath);
  const normalizedWorkspaceRoot = path.normalize(workspaceRoot);
  
  try {
    return path.relative(normalizedWorkspaceRoot, normalizedAbsolutePath);
  } catch (error) {
    // Fallback if relative path calculation fails
    return normalizedAbsolutePath;
  }
}

/**
 * Checks if a file or directory is hidden (starts with '.')
 */
export function isHiddenPath(filePath: string): boolean {
  const normalizedPath = path.normalize(filePath);
  const pathSegments = normalizedPath.split(path.sep);
  
  // Check if any segment in the path starts with '.' (excluding '.' and '..')
  return pathSegments.some(segment => 
    segment.startsWith('.') && segment !== '.' && segment !== '..'
  );
}

/**
 * Checks if a path is in an ignored directory (node_modules, .git, etc.)
 */
export function isPathInIgnoredDirectory(filePath: string): boolean {
  const ignoredDirs = [
    'node_modules',
    '.git',
    '.svn',
    '.hg',
    '.bzr',
    'dist',
    'build',
    'out',
    'target',
    '.next',
    '.nuxt',
    '.output',
    '.vercel',
    '.netlify',
    'coverage',
    '.nyc_output',
    '.cache',
    '.temp',
    '.tmp'
  ];
  
  const normalizedPath = path.normalize(filePath);
  const pathSegments = normalizedPath.split(path.sep);
  
  // Check for hidden paths first
  if (isHiddenPath(filePath)) {
    return true;
  }
  
  return pathSegments.some(segment => ignoredDirs.includes(segment));
}

/**
 * Validates that a path exists and is accessible
 */
export async function validatePath(dirPath: string): Promise<{ valid: boolean; error?: string }> {
  try {
    const fs = await import('fs/promises');
    const stats = await fs.stat(dirPath);
    
    if (!stats.isDirectory()) {
      return { valid: false, error: `Path ${dirPath} is not a directory` };
    }
    
    // Try to read the directory to check permissions
    await fs.readdir(dirPath);
    
    return { valid: true };
  } catch (error) {
    const message = error instanceof Error ? error.message : String(error);
    return { valid: false, error: `Cannot access directory ${dirPath}: ${message}` };
  }
}

/**
 * Creates a safe collection name for Qdrant from a workspace path
 */
export function createCollectionName(workspacePath: string): string {
  const crypto = require('crypto');
  const hash = crypto.createHash('sha256').update(workspacePath).digest('hex');
  return `ws-${hash.substring(0, 16)}`;
}
